// pages/teacher/xiaoxi/detail/detail.js
Page({
  data: {
    id: null,
    message: null,
    loading: true
  },
  
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.fetchMessageDetail(options.id);
    }
  },
  
  // 获取消息详情
  fetchMessageDetail: function(id) {
    wx.request({
      url: `http://localhost:3000/api/teacher/messages/${id}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            message: res.data,
            loading: false
          });
        }
      },
      fail: () => {
        // 使用模拟数据
        const mockMessage = {
          id: id,
          title: '教务处通知',
          content: '各位老师：\n\n请于本周五前提交期末考试试卷，试卷要求包含选择题、填空题和应用题，难度适中，考察学生对本学期知识点的掌握情况。\n\n试卷提交后请等待教研室审核，审核通过后方可印刷。\n\n如有疑问，请联系教务处。',
          time: '2023-12-18 10:30',
          sender: '教务处',
          senderAvatar: '/images/system_avatar.png',
          attachments: [
            {
              name: '试卷模板.docx',
              size: '245KB',
              url: '#'
            },
            {
              name: '考试安排表.xlsx',
              size: '132KB',
              url: '#'
            }
          ]
        };
        
        this.setData({
          message: mockMessage,
          loading: false
        });
      }
    });
  },
  
  // 下载附件
  downloadAttachment: function(e) {
    const url = e.currentTarget.dataset.url;
    if (url === '#') {
      wx.showToast({
        title: '模拟下载成功',
        icon: 'success'
      });
      return;
    }
    
    wx.showLoading({
      title: '下载中...',
    });
    
    wx.downloadFile({
      url: url,
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            success: function() {
              console.log('打开文档成功');
            },
            fail: function() {
              wx.showToast({
                title: '打开文件失败',
                icon: 'none'
              });
            }
          });
        }
      },
      fail: function() {
        wx.hideLoading();
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        });
      }
    });
  }
});